package com.service;

import com.controller.User;
import com.dao.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;

//@Service("userService")
public class UserServiceImpl implements UserService{

    private SqlSession sqlSession;

    public SqlSession getSqlSession() {
        return sqlSession;
    }

    public void setSqlSession(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }

    public UserMapper getUserMapper(){
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//            inputStream = ClassLoader.getSystemResourceAsStream("sqlMapConfig.xml");
            System.out.println(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        final SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = build.openSession();
        final UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        return userMapper;
    }

    @Override
    public User selectUserByUsernameAndPassword(String username, String password) {
        UserMapper userMapper = getUserMapper();
        final User user = userMapper.selectUserByUsernameAndPassword(username, password);
        sqlSession.close();
        return user;
    }

    @Override
    public int addUser(User user)throws Exception {
        UserMapper userMapper = getUserMapper();
        int i = userMapper.addUser(user);
        //异常发生
        int j = 1 / 0; //
        sqlSession.commit();
        return i;
    }

    @Override
    public void loginUserLog(String username, String status, String time) {
        UserMapper userMapper = getUserMapper();
        userMapper.loginUserLog(username,status,time);
        sqlSession.commit();
        sqlSession.close();
        System.out.println(username);
    }

    @Override
    public void registerLog(User user, String status, String time) {
        UserMapper userMapper = getUserMapper();
        userMapper.registerLog(user, status, time);
        sqlSession.commit();
        sqlSession.close();
    }
}
